<?php

class ErrorComponent extends BlueprintComponent {
	
	function parse(&$element, $field = null) {
		$doc = $element->document;
		
		$space = $element->attributes['class'] ? ' ' : '';
		
		if ($field) {
			$element->attributes['class'] .= "<?php echo \$errors['$field'] ? '{$space}error' : '' ?>";
			if ($element->nodeName == 'label') {
				$element->insertBefore($doc->createPHPTextNode("\$errors['$field'] ? '*' : ''"), $element->firstChild);
			}
		} else {
			$element->parentNode->insertBefore($doc->createPHPNode('if ($errors) {'), $element);
			$element->parentNode->insertBefore($doc->createPHPNode('}'), $element->nextSibling);
			$element->attributes['class'] .= "{$space}error";
			$h4 = $doc->createElement('h4');
			$h4->appendChild($doc->createTextNode('The following errors have occured'));
			$element->appendChild($h4);
			$ul = $doc->createElement('ul');
			$element->appendChild($ul);
			$ul->appendChild($doc->createPHPNode('foreach ($errors as $error) {'));
			$li = $doc->createElement('li');
			$ul->appendChild($li);
			$li->appendChild($doc->createPHPTextNode('$error'));
			$ul->appendChild($doc->createPHPNode('}'));
		}
	}
}
?>